<template>
  <gui-page ref="guiPage" :customHeader="true">
    <template v-slot:gHeader>
      <nav-bar-custom left-icon="left" :title="$t('translationImage.processInspection')"></nav-bar-custom>
    </template>
    <template v-slot:gBody>
      <view class="pqcInput page-auto" :style="'height: calc(100vh - '+ navHeight +'px);'">
        <view class="gui-flex gui-rows gui-nowrap gui-align-items-center" style="margin: 20rpx 0;">
          <view class="gui-title-line"></view>
          <text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{
              props.testTypeCode === 'FPH' ? $t('materials.nondestructiveMeasurement') : $t('materials.destructiveMeasurement')
            }}
          </text>
          <view class="gui-title-line"></view>
        </view>
        <view class="element-auto">
          <view class="h-table" style="background-color: #fff;">
            <view class="h-tr h-tr-5 h-thead">
              <view class="h-td h-td-left" style="width: 40%;">
                <view>
                  <view>{{ $t('translationImage.process') }}： {{ props.processName }}</view>
                </view>
              </view>
              <view class="h-td h-td-colspan h-td-left">
                <view style="width: 100%;">
                  <view class="h-td-left" style="display: flex; align-items: center;">
                    {{ $t('multilingual.productionLine') }}：
                    <superweiCombox style="text-align: right;width: 60%;" :candidates="data.productLineS"
                                    :placeholder="$t('distributedOut.placeholder')" :isJSON="true"
                                    keyName="productionLineCode" v-model="data.productLineText"
                                    @select="pullSelect">
                    </superweiCombox>
                  </view>
                </view>
              </view>
            </view>
            <view class="h-tr h-tr-5 h-thead">
              <view class="h-td h-td-left" style="width: 40%;">
                <view>
                  <view>{{ $t('translationImage.classes') }}： {{ props.shiftCode }}</view>
                </view>
              </view>
              <view class="h-td h-td-colspan h-td-left">
                <view style="width: 100%;">
                  <view>
                    {{ $t('materials.startCheckTime') }}：{{ props.checkDate }}
                  </view>
                </view>
              </view>
            </view>
            <view class="h-tr h-tr-5 h-thead ">
              <view class="h-td">{{ $t('materials.inspectionItem') }}</view>
              <view class="h-td">{{ $t('distributedEnter.uom') }}</view>
              <view class="h-td">{{ $t('translationImage.standard') }}</view>
              <view class="h-td">{{ $t('translationImage.inspectionResult') }}</view>
              <view class="h-td">{{ $t('translationImage.supportingInfo') }}</view>
            </view>
            <view class="h-tr h-tr-5" v-for="(x,i) in data.testList" :key="i"
                  :class="{'passclass' : data.qualifiedList[i] == 'pass'},{'failClass' : data.qualifiedList[i] == 'fail'}">
              <view class="h-td">{{ x.checkItemName }}</view>
              <view class="h-td">{{ x.unit }}</view>
              <view class="h-td">{{ x.standardItem }}</view>
              <view class="h-td">
                <view class="gui-flex gui-align-items-center" v-if="!(x.resultType == 'option' && x.isDisabled)">
                  <input v-if="x.resultType == 'text'" type="text"
                         style="width: 120rpx;font-size: 14px;" adjust-position v-model="x.checkResult"
                         :disabled="x.isDisabled">
                  <input v-else-if="x.resultType == 'number'" type="number"
                         style="width: 120rpx;font-size: 14px;" adjust-position v-model="x.checkResult"
                         :disabled="x.isDisabled">
                  <superweiCombox v-else-if="x.resultType == 'option'"
                                  style="text-align: right;width: 120rpx;padding:0"
                                  :candidates="data.selectedList" :placeholder="$t('translationImage.choose')"
                                  :isJSON="true" keyName="text" :defaultValue="data.objFilter[x.checkResult]"
                                  @select="selectFn($event,i)"></superweiCombox>
                </view>
                <view class="gui-flex gui-align-items-center" v-else>
                  {{ x.checkResult == 'pass' ? $t('translationImage.qualified') : (x.checkResult == 'fail' ? $t('translationImage.qualifiedNo') : x.checkResult) }}
                </view>
              </view>
              <view class="h-td">
                <view class="custom-td-operate" @click="rowClick(i)">
                  {{ $t('translationImage.operation') }}
                </view>
              </view>
            </view>
          </view>

          <view class="pqcInput-res">
            {{ $t('translationImage.conclusion') }}：{{ totalQualified }}
          </view>
        </view>
        <!-- 底部操作栏 -->
        <view class="page-bottom-box" v-if="!data.isResult">
          <view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submit">
            {{ $t('calendar.submit') }}
          </view>
        </view>
      </view>
      <!-- 页面弹窗 -->
      <uni-popup ref="inputDialog" type="center">
        <view class="input-dialog-box">
          <view class="input-dialog-content">
            <view class="example-body">
              <uni-file-picker :auto-upload='false' @select="select" v-model="data.uploadImg"
                               :readonly="data.testList[data.imgIndex].isDisabled"></uni-file-picker>
              <view style="line-height: 30px;" v-if="!data.uploadImg.length && data.testList[data.imgIndex].isDisabled">
                {{ $t('translationImage.notAvailableImg') }}
              </view>
            </view>
          </view>
          <view class="input-dialog-footer" v-if="!data.testList[data.imgIndex].isDisabled">
            <view class="input-dialog-button" @click="cancelFn">
              {{ $t('popup.cancel') }}
            </view>
            <view class="input-dialog-button dialog-button-left" @click="confirmFn">
              {{ $t('popup.confirm') }}
            </view>
          </view>
        </view>
      </uni-popup>
    </template>
  </gui-page>
</template>

<script setup>
import {
  TEST_URL,
  PROD_URL,
  IMG_BASE_URL
} from '@/constant/config.js'
import {basPdaOperationLogFn} from '@/utils/index.js';
import {OPERATION_COMMIT} from '@/constant/index.js'
import superweiCombox from '@/components/superweiCombox';
import {
  TOKEN
} from '@/constant/index.js';
import {
  onMounted,
  reactive,
  ref,
  watchEffect,
  computed
} from 'vue'
import {
  selectCheckProject,
  selectMeetLineSecond,
  insertPQCCheckResult,
  selectLastResultById
} from '@/api/api.js'
import {
  navigateBack
} from '@/utils/routerSkip.js';
import {
  getDataDictionaryFn
} from '@/utils/index.js'
import {
  useStore
} from "vuex";

//JS国际化引入
import {useI18n} from 'vue-i18n';

components: {
  superweiCombox
}
const {t} = useI18n();

let store = useStore();
const props = defineProps({
  testTypeCode: String,
  shiftCode:String,
  processCode:String,
  processName:String,
  productionLineName:String,
  barcode:String,
  pickPosition:String,
  startCheckTime:String,
  endCheckTime:String,
  fphStarCheckTime:String,
  fphEndCheckTime:String,
  pqcCount:String,
  checkDate:String,
  linePick:String,
  status:String,
})
let inputDialog = ref(null)

const data = reactive({
  testList: [],
  commitBool: false,//能否提交的标识
  productLineS: [],
  productLineId: '',
  productLineText: '',
  productLineCode:'',
  uploadImg: [],
  selectedList: [{
    text: t('translationImage.qualified'),
    value: 'pass'
  }, {
    text: t('translationImage.qualifiedNo'),
    value: 'fail'
  },],
  imgIndex: 0, //用户当前点击行数索引
  qualifiedList: [], //每一项的检验结果集合
  isPassImgRequired: false, //判断合格是否必须上传图片
  isFailImgRequired: false, //判断不合格是否必须上传图片
  isResult: false, //判断是否有结果
  objFilter: {
    pass: t('translationImage.qualified'),
    fail: t('translationImage.qualifiedNo'),
  }
})
// 判断所有数据是否合格
const totalQualified = computed(() => {
  console.log(data.qualifiedList, 'data.qualifiedListdata.qualifiedListdata.qualifiedList')
  let isTrue = data.qualifiedList.every(x => {
    return x === 'pass'
  })
  let isFail = data.qualifiedList.some(x => {
    return x === 'fail'
  })
  if (isTrue) {
    return t('translationImage.qualified')
  } else if (isFail) {
    return t('translationImage.qualifiedNo')
  } else {
    return ''
  }
})
//页面标题高度
const navHeight = computed(() => {
  return store.state.navHeight
})
// 算出表格每行合格量和总合格数
watchEffect(() => {
  console.log(data.testList)
  //pass 合格 ; fail 不合格
  data.testList.forEach((x, i) => {
    console.log(x.checkResult, i, 'watchEffect')
    if (x.checkResult) {
      switch (x.resultType) {
        case 'text':
          //如果是文字类型，不做判断，默认合格
          data.qualifiedList[i] = 'pass'
          break;
        case 'number':
          //如果是数值类型，判断是否在合格区间
          let a = x.standardItem.split('~')
          let b = Number(a[0])
          let c = Number(a[1])
          let d = Number(x.checkResult)
          if (!isNaN(d) && d >= b && d <= c) {
            data.qualifiedList[i] = 'pass'
          } else {
            data.qualifiedList[i] = 'fail'
          }
          break;
        case 'option':
          data.qualifiedList[i] = x.checkResult
          break;
        default:
          break;
      }
    } else {
      data.qualifiedList[i] = ''
    }
  })
})

onMounted(() => {
  selectCheckProjectFn()
  getInitData()
})

const selectLastResultByIdFn = (id) => {
  selectLastResultById({
    masterId: id,
    testTypeCode: props.testTypeCode,
  }).then(res => {
    console.log('产线结果', res)
    if (res.status == 200 && res.data.length > 1) {
      if (res.data[0].checkResult) {
        data.testList = res.data;
        data.testList.forEach(x => {
          x.imgList = []
          // 禁用逻辑
          switch (x.resultType) {
            case 'text':
              //如果是文字类型，不做判断，默认合格
              x.isDisabled = true;
              break;
            case 'number':
              //如果是数值类型，判断是否在合格区间
              let a = x.standardItem.split('~')
              let b = Number(a[0])
              let c = Number(a[1])
              let d = Number(x.checkResult)
              if (!isNaN(d) && d >= b && d <= c) {
                x.isDisabled = true;
              } else {
                x.isDisabled = false;
              }
              break;
            case 'option':
              if (x.checkResult == 'pass') {
                x.isDisabled = true;
              } else {
                x.isDisabled = false;
              }
              break;
            default:
              break;
          }
          // 图片逻辑
          if (x.supportImage) {
            x.imgList = x.supportImage.split(',').map(x => {
              return {
                name: '',
                extname: 'png',
                url: x
              }
            })
          }
        })
        console.log('处理数据', data.testList)
      } else {
        data.testList = res.data;
        data.qualifiedList = []
        data.testList.forEach(x => {
          x.imgList = []
          data.qualifiedList.push('')
          if (x.supportImage) {
            x.imgList = x.supportImage.split(',').map(x => {
              return {
                name: '',
                extname: 'png',
                url: x
              }
            })
          }
        })
      }
      // 检测当前产线能否提交
      data.commitBool = data.testList.every(x => {
        return x.checkResult
      })
    }
  })
}

// 下拉列表选择
const selectFn = (e, index) => {
  data.testList[index].checkResult = e.value
}
// 提交
const submit = () => {
  if (!data.productLineId) {
    uni.showToast({
      title: t('JsInternational.chooseLine'),
      icon: 'none'
    })
    return
  }
  if (data.commitBool) {
    uni.showToast({
      title: t('materials.submittedRepeatedly'),
      icon: 'none'
    })
    return
  }

  // 检测每行检测结果是否填写
  let isTrue = data.testList.every(x => {
    return x.checkResult
  })
  console.log(isTrue)
  if (!isTrue) {
    uni.showToast({
      title: t('JsInternational.plsFillAll'),
      icon: 'none'
    })
    return
  }
  // 检测合格结果佐证资料是否必填
  if (!data.isPassImgRequired) {
    if (!data.testList.every(x => x.imgList.length)) return uni.showToast({
      title: t('materials.pleaseUploadSupporting'),
      icon: 'none'
    })
  }
  // 检测不合格结果佐证资料是否必填
  if (!data.isFailImgRequired) {
    if (!data.testList.every(x => x.imgList.length)) return uni.showToast({
      title: t('materials.pleaseUploadSupportingInfo'),
      icon: 'none'
    })
  }

  uni.showModal({
    content: t('JsInternational.submitConfirm'),
    success: (res) => {
      if (res.confirm) {
        submitInterface()
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    }
  });
}

const submitInterface = () => {
  data.testList.forEach(x => {
    let arry = x.imgList.map(x => x.url)
    console.log(arry)
    x.supportImage = arry.join()
  })
  let parmes = {
    id: data.productLineId,
    testTypeCode: props.testTypeCode,
    qmsPqcCheckDS: data.testList,
  }
  insertPQCCheckResult(parmes).then(res => {
    try {
      let inputParameter = JSON.stringify(parmes)
      let returnParameter = JSON.stringify(res)
      let operationPicture = '过程检验'
      let callInterface = res.rquestUrl
      let opertionParmes = {
        inputParameter,
        returnParameter,
        operationPicture,
        callInterface,
        responseCode: res.status,//返回状态
        errorMessage: res.message,//错误信息
        isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
        operationType: OPERATION_COMMIT
      }
      basPdaOperationLogFn(opertionParmes)
    } catch (error) {
    }
    if (res.status == 200) {
      uni.showToast({
        title: t('smashRemoval.submitSuccessfully'),
        icon: 'none',
        complete: () => {
          navigateBack()
        }
      })
    } else {
      uni.showToast({
        title: res.message,
        icon: "none"
      });
    }
  })
}

// 产线选择
const pullSelect = (e) => {
  console.log(e.id, '产线选择');
  data.productLineId = e.id;
  selectLastResultByIdFn(data.productLineId)
}

// 表格点击操作
const rowClick = (index) => {
  data.imgIndex = index;
  data.uploadImg = data.testList[index].imgList;
  console.log(data.uploadImg, 'data.uploadImg');
  inputDialog.value.open();
}

const getInitData = async () => {
  // 控制PDA质检画面的佐证资料是否需要上传照片
  let info = await getDataDictionaryFn('SupportingInformation')
  info.forEach(x => {
    if (x.value === 'pass') {
      data.isPassImgRequired = x.selected
    } else if (x.value === 'fail') {
      data.isFailImgRequired = x.selected
    }
  })
  console.log(data, 'getInitData')
}

// 过程检测查询检测项目
const selectCheckProjectFn = () => {
  selectCheckProject({
    processCode: props.processCode,
    shiftCode: props.shiftCode,
    pqcCount: props.pqcCount,
    checkDate: props.checkDate,
    testTypeCode: props.testTypeCode
  }).then(res => {
    console.log(res);
    if (res.status == 200) {
      data.testList = res.data;
      data.qualifiedList = []
      data.testList.forEach(x => {
        x.imgList = []
        data.qualifiedList.push('')
        if (x.supportImage) {
          x.imgList = x.supportImage.split(',').map(x => {
            return {
              name: '',
              extname: 'png',
              url: x
            }
          })
        }
      })
    } else {
      uni.showToast({
        title: res.message,
        icon: "none"
      });
    }
    selectMeetLineSecondFn()
  })
}

// 过程检测查询检测项目的符合产线
const selectMeetLineSecondFn = () => {
  selectMeetLineSecond({
    processCode: props.processCode,
    shiftCode: props.shiftCode,
    pqcCount: props.pqcCount,
    checkDate: props.checkDate,
    testTypeCode: props.testTypeCode,
    selectType: 'detail'
  }).then(res => {
    console.log(res);
    if (res.status == 200) {
	    data.productLineS = res.data;
      if (data.productLineS.length == 1) {
        data.productLineId = data.productLineS[0].id
        data.productLineText = data.productLineS[0].productionLineName
		data.productLineCode = data.productLineS[0].productionLineCode
        selectLastResultByIdFn(data.productLineId)
      }
    } else {
      uni.showToast({
        title: res.message,
        icon: "none"
      });
    }
  })
}

// 上传图片获取开始上传
const select = (e) => {
  const tempFilePaths = e.tempFilePaths;
  let isDev = process.env.NODE_ENV === 'development';
  let baseUrl = isDev ? TEST_URL : PROD_URL
  let token = uni.getStorageSync(TOKEN);
  let formData = {
    // bizId: props.processCode,
    bizId: data.productLineId,
    bizType: 'qms_pqc_check_h',
    status: 0
  }
  uni.showLoading({
    title: t('JsInternational.uploading')
  });
  for (var i in tempFilePaths) { //多文件
    uni.uploadFile({
      url: baseUrl + '/system/oss/oss-simple', //上传接口
      name: 'file',
      header: {
        // "content-type": "multipart/form-data",
        'token': token
      },
      filePath: tempFilePaths[i],
      formData: formData,
      success: (uploadFileRes) => {
        uni.hideLoading();
        const back = JSON.parse(uploadFileRes.data);
        if (back.statusCode == 200) {
          // let imgPath = IMG_BASE_URL + back.filePath;
          let imgPath = back.data;
          data.uploadImg.push({
            name: '',
            extname: 'png',
            url: imgPath
          })
        } else {
          uni.showToast({title: back.message, icon: "none"});
        }
      },
      fail: () => {
        uni.hideLoading();
        uni.showToast(t('JsInternational.pictureUploading'))
      },
      complete: function () {
        uni.hideLoading();
      }
    });
  }
}

const cancelFn = () => {
  inputDialog.value.close();
  data.uploadImg = []
}

const confirmFn = () => {
  data.testList[data.imgIndex].imgList = data.uploadImg
  inputDialog.value.close();
}
</script>

<style lang="scss">
:deep .superweiCombox__selector {
  left: 0rpx !important;
  right: 0rpx !important;
}

.gui-align-items-center {
  position: relative;
}

.h-td-left {
  position: relative;
}

.custom-td-operate {
  display: inline-block;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  background: #3970E6;
  color: #fff;
  line-height: 28rpx;
}

.pqcInput-res {
  text-align: right;
  font-size: 32rpx;
  padding: 30rpx;
}
</style>
